package com.coship.vas.dapg.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
/**
 * http post 工具类
 * @author 904912
 *
 */
public class HttpPostUtils {

    public static String post(String url, String reuqest, String encoding) throws Exception {
        OutputStreamWriter out = null;
        String response = "";
        URL httpUrl = new URL(url);
        URLConnection con = httpUrl.openConnection();
        con.setDoOutput(true);
        con.setRequestProperty("Pragma:", "no-cache");
        con.setRequestProperty("Cache-Control", "no-cache");
        con.setRequestProperty("Content-Type", "text/xml");
        HttpURLConnection http = (HttpURLConnection) con;
        http.setRequestMethod("POST");
        http.setConnectTimeout(2000);
        http.setReadTimeout(60000);
        out = new OutputStreamWriter(con.getOutputStream(), encoding);
        out.write(reuqest);
        out.flush();
        out.close();
        if (http.getResponseCode() == HttpURLConnection.HTTP_OK) {
            BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(),encoding));
            String line = "";
            for (line = br.readLine(); line != null; line = br.readLine()) {
                response += line+"\r\n";
            }
            br.close();
        } else {
            response = String.valueOf(http.getResponseCode());
        }

        return response;
    }

    public static void main(String[] args) {
        String content = "<?xml version=\"1.0\"?> <methodCall>" +
        		"<methodName>prgrelation</methodName><params>" +
        		"<param><value><int>38054</int></value></param>" +
        		"<param><value><int>80</int></value></param>" +
        		"<param><value><int>1</int></value></param>" +
        		"<param><value><int>1</int></value></param>" +
        		"</params></methodCall>";

        try {
          String response =  post("http://www.tvibe.com/iepg/tv.php", content, "utf-8");
          System.out.println(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
